// useDraggable.js  
import { ref, onMounted, onUnmounted, watch } from 'vue';  
export function useDraggable(elementRef, bounds = { left: 0, top: 0, right: window.innerWidth, bottom: window.innerHeight }) {  
    
  const position = ref({ x: 0, y: 0 });  
  const isDragging = ref(false);  
  const startX = ref(0);  
  const startY = ref(0);  
  let max = 0;
  let min = 0;
  
  let maxY = 0;
  let minY = 0;
  const updatePosition = (event) => {  
    if (!isDragging.value) return;  
    const rect = elementRef.value.getBoundingClientRect();  
      var newX = event.clientX - startX.value;  
      var newY = event.clientY - startY.value; 
      if(newX < min){
        newX = min
      }
      if(newX > max){
        newX = max
      }

      if(newY < minY){
        newY = minY
      }
      if(newY > maxY){
        newY = maxY
      }
      position.value = { x: newX, y: newY };  
    // 更新DOM样式  
    elementRef.value.style.transform = `translate(${newX}px, ${newY}px)`;  
  };
  const handleMouseDown = (event) => {  
    
    // if (event.target.tagName.toLowerCase() !== 'div' || !event.target.classList.contains('draggable-title')) return;  
    if (!(event.target.closest('.draggable-title'))) return;
  
    isDragging.value = true;  
    startX.value = event.clientX - position.value.x;  
    startY.value = event.clientY - position.value.y;  
  
    document.addEventListener('mousemove', updatePosition);  
    document.addEventListener('mouseup', handleMouseUp);  
  };  
  
  const handleMouseUp = () => {  
    isDragging.value = false;  
    document.removeEventListener('mousemove', updatePosition);  
    document.removeEventListener('mouseup', handleMouseUp);  
  };  
  const initData = ()=>{
    
   if (elementRef.value) {
    const rect = elementRef.value.getBoundingClientRect();  
    max = window.innerWidth - rect.right + position.value.x;
    min = -rect.left +  position.value.x;

    maxY = window.innerHeight - rect.bottom +position.value.y;
    minY = -rect.top +position.value.y;

   }
    
  }
  onMounted(() => {  
    if (elementRef.value) {  
      initData()
     window.addEventListener("resize",initData)
      elementRef.value.addEventListener('mousedown', handleMouseDown);  
    }  
  });  
  
  onUnmounted(() => {  
    if (elementRef.value) {  
      elementRef.value.removeEventListener('mousedown', handleMouseDown); 
     window.removeEventListener("resize", initData) 
    }  
  });  
  
  return { position,initData };  
}